package com.zlp.validator.impl;

import com.zlp.chain.Handler;
import com.zlp.dto.PromoContext;
import com.zlp.dto.PromoInDTO;
import com.zlp.dto.SkuDTO;
import com.zlp.props.PromoProperties;
import com.zlp.validator.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: gubin
 * @date: 2022/8/11 16:08
 * @description:
 */
@Slf4j
@Component
public class StockValidator extends Validator implements InitializingBean {

    @Autowired
    private PromoProperties promoProperties;

    @Autowired
    private Handler confirmHandler;

    @Override
    public void afterPropertiesSet() {
        confirmHandler.getValidators().put(2, this);
    }


    @Override
    public void validate(SkuDTO skuDTO) {
        int skuId = skuDTO.getId();
        PromoContext occ = PromoContext.get();
        String memberId = occ.getMemberId();
        int quantity = skuDTO.getQuantity();
      /*  String keyStock = PromoConst.seckillStockKey + "{" + skuId + "}";
        String keyLimit = PromoConst.seckillLimitKey + "{" + skuId + "}" + "-" + memberId;
//                + "-" + DateTimeFormatter.ofPattern("MMdd").format(LocalDateTime.now());
        DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptText(promoProperties.getLuaDeductStock());
//        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("seckill.lua")));
        Long stock = redisTemplate.execute(defaultRedisScript, Arrays.asList(keyStock, keyLimit), quantity + "", skuDTO.getLimit() + "");
        log.info("StockValidator validate stock:{}",stock);
        if (ObjectUtils.isEmpty(stock)) {
            throw new CustomException(ErrorEnum.DEDUCT_STOCK_ERROR);
        }
        if (stock == -1) {
            log.info("{}：已售罄", skuId);
            throw new CustomException(ErrorEnum.SOLD_OUT_ERROR);
        } else if (stock == -2) {
            log.info("memberId: {}, skuId: {} 购买超限", memberId, skuId);
            throw new CustomException(ErrorEnum.REPEAT_BUY_ERROR);
        } else {
            String startTime = System.currentTimeMillis() + "";
            log.info("{}：库存扣除成功，剩余库存：{} {}", skuId, stock, startTime);
            String reqNo = IdUtil.objectId();
            occ.setReqNo(reqNo);
        }*/
    }

    @Override
    public void validate(PromoInDTO promoInDTO) {
    }
}
